$(function () {
	//游戏名称
	var gameName = 'redpackage-rain';
	//触摸点距离盒子的距离
	var box_x,box_y;
	//计时器,计数器
	var timerCounter,guostCounter;
	//全局计数变量
	var globalNum = 0;
	//吃多少鸡算成功
	var totalGuost = 1;
	//创建计时器
	var timer,moveTimer;
	//游戏区域的高度
	var gameAreaHeight = $(window).height();

	//判断用户是否有抽奖(游戏)资格
	api.eligibleToPlay(uid, act_id, vote_token);
	//获取活动参数
	api.getGameConfig(act_id, gameName);

	//点击[我要抢红包]按钮
	$('#startBtn').on('click',function () {
		if (limitNum <= 0) {
			Toast('游戏次数不够');
			return;
		};
		$('#startPage').hide();
		$('#rulePage').show();
		var n = 3;
		var timer = setInterval(function () {
			n--;
			if (n === 2) {
				$('#number').css('background-position-y', '-1.9rem');
			} else if (n === 1) {
				$('#number').css('background-position-y', '0');
			} else {
				clearInterval(timer);
				$('#rulePage').hide();
				$('#gamePage').show();
				$('#number').css('background-position-y', '-3.8rem');
				gameBegin();
			}
		},1000);
	});

	//红包的点击事件
	$('#gamePage').on('click', '.chicken', function () {
		$(this).addClass('chicken-a');
		guostCounter++;
	})

	//点击[抽奖]按钮
	$('#successLottery').on('click', function  () {
		$('#toast-content').text('抽奖中...');
		$('#toast-box').show();
		api.lottery(act_id, gameName, uid, function(res){
			$('#successBox,#toast-box').hide();
			if (res.code == 200) {
				if (res.data.is_winning) {
					$('#prize-name').text(res.data.prize.name);
					$('#lotterySuccessBox').show();
				} else {
					$('#lotteryFailBox').show();
				}
			} else {
				$('#successPage').hide();
				$('#startPage').show();
				Toast(res.message);
			}
		})
	})

	//游戏开始
	function gameBegin() {
		//次数减少一次
		limitNum--;
		//初始化
		timerCounter = 9;
		guostCounter = 0;
		globalNum = 0;
		$('#timeCounter').text(timerCounter);
		//倒计时
		timer = setInterval(function () {
			timerCounter--;
			$('#timeCounter').text(timerCounter);
			if (timerCounter === 0) {
				clearInterval(timer);
				clearInterval(moveTimer);
				$('#gamePage').hide();
				$('#resultBox').show();
			};
		}, 1000);
		//移动事件
		guostMove();
		moveTimer = setInterval(guostMove,1000/60);
	};

	//移动事件
	function guostMove() {
		//定时生成鸡或者炸弹
		if (globalNum%15 === 0) {
			createItem();
		};
		var guosts = $('.chicken');
		guosts.map(function (ele, i) {
			var item_top = i.offsetTop;
			var item_left = i.offsetLeft;
			//清除已经超出边界的
			if (item_top > gameAreaHeight) {
				$(this).remove();
				return;
			} else {
				i.style.top = item_top + 5 + 'px';
				i.style.left = item_left -1 + 'px';
			};
		});
		globalNum++;
	};
	//随机生成鸡或者炸弹
	function createItem() {
		//父盒子宽度7.5rem 物品宽度1rem;
		//left值随机范围 0 - 6.5rem;
		//产生随机数
		var num = (Math.random()*6.5).toFixed(1);
		var html = '<div class="chicken" style="top:0;left:'+num+'rem"></div>';
		$('#gameArea').append(html);
	};
});